<template>
  <!-- 法规平台 -->
  <div class="app-container">
    <!-- <h1>法规平台</h1> -->
    <el-button
      @click="dialogVisible = true"
      style="margin-bottom: 30px"
      type="primary"
      >添加</el-button
    >
    <div class="boxlaw">
      <div slot="header" class="clearfix">
        <ComSelect @EventChange="ChangeFn" :options="options"></ComSelect>
      </div>

      <div class="comform">
        <ComForm
          ref="comForm"
          @EventReset="resetFn"
          @EventOnsubmit="queryFn"
          :list="comForm"
        >
        </ComForm>
      </div>

      <ComTable
        @handleCurrentChange="CurrentPageChangeFn"
        @handleSizeChange="currentPageSizeChangeFn"
        :key="random"
        :list="tableList"
        :modes="tableModes"
        :config="{ border: true, loading }"
        :pagination="{ total: paging.total, pageNum: paging.pageNum }"
      >
        <el-table-column width="240" #default="{ row }" align="left">
          <template>
            <el-button
              @click="editFn(row)"
              plain
              size="mini"
              type="primary"
              v-hasPermi="['market:coupon:edit']"
              >修改</el-button
            >
            <el-button
              plain
              size="mini"
              type="primary"
              v-hasPermi="['market:coupon:remove']"
              @click="deleteFn(row)"
              >删除</el-button
            >
            <el-button
              v-hasPermi="['market:coupon:getInfo']"
              @click="clickLook(row)"
              plain
              size="mini"
              type="primary"
              >发行详细</el-button
            >
          </template>
        </el-table-column>
      </ComTable>
      <NewlyAdd
        :dict="dict"
        :editId.sync="editId"
        @getListEven="getCouponListFn"
        :dialogVisible.sync="dialogVisible"
      ></NewlyAdd>
    </div>
  </div>
</template>

<script>
import ComForm from "../../../components/comForm.vue";
import ComSelect from "../../../components/comSelect.vue";
import ComTable from "../../../components/comTable.vue";
import comForm from "../../../components/comForm.vue";
import { getLocalTime } from "@/wss/utils/wss.js";
// import { getdocGetTypeApi } from "@/wss/api/ContentSupervision.js";

import {
  getCouponListApi,
  getCouponRemoveApi,
} from "@/wss/api/systemManagement/Cvm/settting.js";
import NewlyAdd from "./newlyAdd.vue";
export default {
  name: "laws",
  dicts: ["sys_normal_disable"],
  components: { ComSelect, ComForm, comForm, ComTable, NewlyAdd },

  data() {
    return {
      // 可用服务列表,value注意要是字符串
      dict: [
        { label: "通用", value: "0" },
        { label: "在线质询", value: "1" },
        { label: "图文质询", value: "2" },
        { label: "解答文档", value: "3" },
      ],
      dialogVisible: false,
      initSelectValue: "",
      // 修改id
      editId: "",
      // 加载
      loading: false,
      paging: { pageNum: 1, pageSize: 10, status: "", total: 10 },
      // 切换筛选状态，不更新bug修复
      random: "",
      // 当前筛选的状态
      currentSelect: "",
      options: {
        value: "",
        title: "快速筛选",
        list: [
          {
            value: "",
            label: "全部",
          },

          {
            value: "0",
            label: "可用",
          },
          {
            value: "1",
            label: "已过期",
          },
        ],
      },
      // 动态生成下拉列表的筛选条件
      dynamicFilter: {},
      // 表格的数据
      tableList: [],
      tableModes: [
        {
          label: "卡券编号",
          mode: "no",
        },
        {
          showOverflowTooltip: true,
          width: 150,

          label: "可用服务",
          mode: "typeName",
          showOverflowTooltip: true,
        },
        {
          label: "可用金额",
          mode: "amount",
        },
        {
          width: 110,
          label: "使用门槛",
          mode: "symk",
          showOverflowTooltip: true,
        },
        {
          label: "已发放（张）",
          mode: "grantNumber",
          showOverflowTooltip: true,
        },
        {
          label: "总数量",
          mode: "sum",
          showOverflowTooltip: true,
        },
        {
          label: "卡券状态",
          mode: "pastDue",
          effectiveStatus: true,
          width: 100,
          align: "center",
          isShowTag: true,
          options: [
            {
              l: "可用",
              v: 0,
            },
            {
              l: "过期",
              v: 1,
              type: "warning",
            },
          ],
        },
        {
          label: "用户权限",
          mode: "permission",
          effectiveStatus: true,
          width: 100,
          align: "center",
          isShowTag: true,
          options: [
            {
              l: "可赠送",
              v: 0,
            },
            {
              l: "不可赠送",
              v: 1,
              type: "warning",
            },
          ],
        },
        {
          label: "有效期",
          mode: "expireTime",
          width: 200,
        },
        {
          label: "创建时间",
          mode: "createTime",
          width: 150,
        },
      ],
      comForm: {
        modes: [
          {
            placeholder: "请输入卡券编号",
            formType: "input",
            mode: "name",
            label: "卡券编号",
            value: "",
          },
          {
            formType: "select",
            mode: "type",
            label: "可用服务",
            value: "",
            select: [],
          },
          {
            formType: "select",
            mode: "permission",
            label: "发布来源",
            value: "",
            select: [],
          },
        ],
      },
    };
  },

  mounted() {
    this.getCouponListFn(this.paging);
  },
  methods: {
    // 修改
    editFn(row) {
      // console.log(row);
      this.dialogVisible = true;
      this.editId = row.idStr;
    },
    async deleteFn(row) {
      try {
        this.$confirm("此操删除该数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            await getCouponRemoveApi(row.idStr);

            this.getCouponListFn();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch((e) => {
            // 系统报错
            if (e.message === "已有用户领取，不能删除") {
            } else {
              // 用户取消
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            }
          });
      } catch (error) {}
    },
    // 重设函数
    resetFn() {
      this.initSelectValue = "";
      this.romdom = Math.random();
      this.options.value = "";
      this.paging.status = "";
      console.log(this.paging, "重设");
    },
    // 当前页发生改变时候
    CurrentPageChangeFn(pageNUm) {
      this.paging.pageNum = pageNUm;
      this.getCouponListFn(this.paging);
    },
    // 页容量发生改变时候
    currentPageSizeChangeFn(pageSize) {
      this.paging.pageSize = pageSize;
      this.getCouponListFn(this.paging);
    },
    // 筛选数据
    queryFn(arr) {
      arr.forEach((item) => {
        for (const key in item) {
          this.paging[key] = item[key];
        }
      });
      this.currentSelect = this.initSelectValue;
      this.paging.pageNum = 1;
      this.getCouponListFn(this.paging);
    },
    // 获取列表数据
    async getCouponListFn() {
      this.loading = true;
      let { rows, code, total } = await getCouponListApi(this.paging);
      // let start = null;
      // let end = null;
      let arr = null;
      console.log(rows, "卡券的数据");
      if (code == 200) {
        this.tableList = JSON.parse(JSON.stringify(rows));
        // 数据改造
        this.tableList.map((item) => {
          arr = item.type.split(",");
          item.type = "";
          // 后端返回的是数值要对应上文字
          this.dict.forEach((v, index) => {
            if (arr.includes(v.value)) {
              item.type += v.label + " / ";
            }
            // console.log(index);
            if (this.dict.length - 1 == index) {
              console.log(item.type);
              item.type.replace(/\/$/, () => {
                return "";
              });
            }
          });

          // 不是按天算
          if (item.expireType !== "1") {
            item.expireTime =
              item.expireStart.split(" ")[0] +
              "~" +
              item.expireEnd.split(" ")[0];
          } else {
            // 按天计算
            item.expireTime = "自领取日起" + item.expireTime + "天内";
          }

          item.symk = "满" + item.symk + "可用";
        });
        this.paging.total = total;
        // 把后端放回的字段变成下拉筛选字段
        //  动态筛选
        this.dynamicFilter.type = [];
        let toRepeat = null;
        rows.forEach((item) => {
          //是否有这个属性
          this.dynamicFilter.permission
            ? ""
            : (this.dynamicFilter.permission = []);

          if (!this.dynamicFilter.permission.includes(item.permission)) {
            this.dynamicFilter.permission.push(item.permission);
          }

          this.dynamicFilter.type.push(...item.type.split("/"));
        });
        // 去重复
        toRepeat = Array.from(new Set(this.dynamicFilter.type));
        // 动态添加上筛选条件
        this.comForm.modes.forEach((item) => {
          switch (item.mode) {
            case "permission":
              item.select = this.arrTransformObj(
                this.dynamicFilter.permission,
                ["未转送", "已转送"]
              );
              break;

            case "type":
              item.select = [];
              this.dict.forEach((v) => {
                console.log(toRepeat.includes(v.label), v.label);
                if (toRepeat.includes(v.value)) {
                  item.select.push(v);
                }
              });

            default:
              break;
          }
        });

        this.loading = false;
      }
    },
    async ChangeFn(value) {
      this.paging.pastDueStatus = value;
      this.getCouponListFn();
    },

    // 查看
    async clickLook(row) {
      this.$router.push({
        path: "/systems/coupon/detailAvailable",
        query: { id: row.idStr },
      });
    },
  },
};
</script>

<style lang ="scss" scoped>
.comform {
  margin-top: 20px;
}
</style>